package com.syl.utils;

import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.HtmlRenderer;

public class ArticleUtils {

  public static String htmlToText(String html) {
    if (StringUtils.isNotBlank(html)) {
      return html.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " ");
    }
    return "";
  }

  public static String mdToHtml(String markdown) {
    if (StringUtils.isBlank(markdown)) {
      return "";
    }
    List<Extension> extensions = List.of(TablesExtension.create());
    Parser parser = Parser.builder().extensions(extensions).build();
    Node document = parser.parse(markdown);
    HtmlRenderer renderer = HtmlRenderer.builder()
        .attributeProviderFactory(context -> new LinkAttributeProvider())
        .extensions(extensions).build();
    String content = renderer.render(document);
    content = Commons.emoji(content);
    return content;
  }

  public static String cleanXSS(String value) {
    value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
    value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
    value = value.replaceAll("'", "&#39;");
    value = value.replaceAll("eval\\((.*)\\)", "");
    value = value.replaceAll("[\"']\\s*javascript:(.*)[\"']", "\"\"");
    value = value.replaceAll("script", "");
    return value;
  }

  private static class LinkAttributeProvider implements AttributeProvider {

    @Override
    public void setAttributes(Node node, String tagName, Map<String, String> attributes) {
      if (node instanceof Link) {
        attributes.put("target", "_blank");
      }
    }
  }
}
